package com.chenwy.example.configuration;

import com.chenwy.example.filter.CrossOriginFilter;
import com.chenwy.example.resolver.CompatibleMultipartResolver;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Configuration
public class WebConfiguration {

    @Value("${cross.origin.allowed-origins}")
    private String allowedOrigins;
    @Value("${cross.origin.allowed-methods}")
    private String allowedMethods;
    @Value("${cross.origin.allowed-credentials}")
    private String allowedCredentials;

    @Bean(name = "crossOriginFilter")
    public CrossOriginFilter crossOriginFilter(){
        CrossOriginFilter filter = new CrossOriginFilter();
        return filter;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean(
            @Qualifier("crossOriginFilter") CrossOriginFilter filter){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(filter);
        registration.addUrlPatterns("/*");
        registration.addInitParameter("allowedOrigins",allowedOrigins);
        registration.addInitParameter("allowedMethods",allowedMethods);
        registration.addInitParameter("allowedCredentials",allowedCredentials);
        registration.setName(filter.getClass().getName());
        return registration;
    }

    @Bean(name="multipartResolver")
    public CommonsMultipartResolver multipartResolver(){
        CompatibleMultipartResolver resolver = new CompatibleMultipartResolver();
        resolver.setExcludeUrls("uploadByServletFileUpload");
        resolver.setDefaultEncoding("utf-8");
        resolver.setMaxUploadSize(10240000);
        resolver.setMaxInMemorySize(10240);
        return resolver;
    }
}
